package com.mingqijia.gassafety.console.controller.inner;

import com.alibaba.fastjson.JSONObject;
import com.gap.basic.base.CommonResponse;
import com.mingqijia.gassafety.db.entity.vo.UserServiceComboVO;
import com.mingqijia.gassafety.shared.constant.ConsoleSkAlarmTypeEnum;
import com.mingqijia.gassafety.shared.constant.ConsoleSkDeviceTypeEnum;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.constant.SkConst;
import com.mingqijia.gassafety.shared.utils.RedisCacheExt;
import com.mingqijia.gassafety.shared.utils.commonUtils.DateUtils;
import com.mingqijia.gassafety.webserver.request.BrowserNotifyReason;
import com.mingqijia.gassafety.webserver.request.ConsumerCreateRequest;
import com.mingqijia.gassafety.webserver.request.ConsumerUnbindRequest;
import com.mingqijia.gassafety.webserver.request.EquipmentPositionRequest;
import com.mingqijia.gassafety.webserver.request.workorder.asst.ContactsEditRequest;
import com.mingqijia.gassafety.webserver.request.workorder.asst.ContactsListRequest;
import com.mingqijia.gassafety.webserver.request.workorder.asst.OrderCompleteRequest;
import com.mingqijia.gassafety.webserver.request.workorder.asst.OrderInfoSyncRequest;
import com.mingqijia.gassafety.webserver.request.workorder.mbp.MbpOrderCreateRequest;
import com.mingqijia.gassafety.webserver.request.workorder.order.OrderSparkOrderRequest;
import com.mingqijia.gassafety.webserver.response.ConsoleSkNotifyAlarmResponse;
import com.mingqijia.gassafety.webserver.response.sk.ConsoleSkRecordsList;
import com.mingqijia.gassafety.webserver.response.workorder.asst.ContactsListResponse;
import com.mingqijia.gassafety.webserver.service.workorder.SyncOrderService;
import com.mingqijia.gassafety.webserver.service.workorder.WorkOrderHistoryService;
import com.mingqijia.gassafety.webserver.service.workorder.mbp.MbpWorkOrderService;
import com.mingqijia.gassafety.webserver.webSocket.WebSocketProcess;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: gassafety
 * @description: 同步时刻助手工单信息
 * @author: Mr.Wang
 * @create: 2022-09-19 13:49
 **/


@Slf4j
@Api(tags = "同步时刻助手工单信息")
@RestController(value = "SyncOrderController")
@RequestMapping("/inner/v1/asst/sync/order")
public class SyncOrderController {


    @Autowired
    private SyncOrderService syncOrderService;

    @Autowired
    RedisCacheExt redisUtil;

    @Autowired
    WorkOrderHistoryService workOrderHistoryService;

    @Autowired
    MbpWorkOrderService mbpWorkOrderService;

    @Autowired
    WebSocketProcess webSocketProcess;

    @ApiOperation("同步用户信息,创建客户并绑定设备")
    @RequestMapping(value = "bindingDtu", method = RequestMethod.POST)
    public CommonResponse<Object> bindingDtu(@RequestBody @Valid ConsumerCreateRequest request) {
        syncOrderService.createConsumerBindImei(request);
        return CommonResponse.success("success");
    }

    @ApiOperation("新时刻同步用户信息,创建客户并绑定设备")
    @RequestMapping(value = "/bindingOrderDtu", method = RequestMethod.POST)
    public CommonResponse<Object> bindingOrderDtu(@RequestBody @Valid ConsumerCreateRequest request) {
        log.info("新时刻同步用户信息,创建客户并绑定设备:{}", JSONObject.toJSON(request));
//        if (StringUtils.isEmpty(request.getMemberId()) && StringUtils.isEmpty(request.getSubsCode())) {
//            throw new BizException("会员id和户号必须有一个必填");
//        }
        syncOrderService.createOrderConsumerBindImei(request);
        return CommonResponse.success("success");
    }

    @ApiOperation("同步设备解绑状态")
    @RequestMapping(value = "unbindEquipment", method = RequestMethod.POST)
    public CommonResponse<Object> unbindEquipment(@RequestBody @Valid ConsumerUnbindRequest request) {
        syncOrderService.unbindEquipment(request);
        return CommonResponse.success("success");
    }

    @ApiOperation("同步设备解绑状态")
    @RequestMapping(value = "unbindOrderEquipment", method = RequestMethod.POST)
    public CommonResponse<Object> unbindOrderEquipment(@RequestBody @Valid ConsumerUnbindRequest request) {
        log.info("同步设备解绑状态:{}", JSONObject.toJSON(request));
//        if (StringUtils.isEmpty(request.getMemberId()) && StringUtils.isEmpty(request.getSubsCode())) {
//            throw new BizException("会员id和户号必须有一个必填");
//        }
        String msg = syncOrderService.unbindOrderEquipment(request);
        return CommonResponse.success(msg);
    }

    @ApiOperation("同步设备安装位置")
    @RequestMapping(value = "equipmentPosition", method = RequestMethod.POST)
    public CommonResponse<Object> equipmentPosition(@RequestBody @Valid List<EquipmentPositionRequest> request) {
        syncOrderService.equipmentPosition(request);
        return CommonResponse.success("success");
    }

    @ApiOperation("同步工单信息")
    @RequestMapping(value = "orderInfo", method = RequestMethod.POST)
    public CommonResponse<Object> orderInfo(@RequestBody @Valid OrderInfoSyncRequest request) {
        syncOrderService.orderInfo(request);
        return CommonResponse.success("success");
    }

    @ApiOperation("工单完成")
    @RequestMapping(value = "orderComplete", method = RequestMethod.POST)
    public CommonResponse<Object> orderComplete(@RequestBody @Valid OrderCompleteRequest request) {
        log.info("时刻助手工单完成:{}", JSONObject.toJSON(request));
        syncOrderService.orderComplete(request);
        return CommonResponse.success("success");
    }

    @ApiOperation("工单调试")
    @RequestMapping(value = "/orderSpark" , method = RequestMethod.POST)
    public CommonResponse<Object> spark(@RequestBody @Valid OrderSparkOrderRequest request){
        Integer state;
        if( null == request.getState() ){// 查询调试状态
            state = syncOrderService.sparkStatus(request);
        }else{ // 创建/取消点火,安检工单
            state = syncOrderService.spark(request);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("state",state);
        return CommonResponse.success(map);
    }

    @ApiOperation("安防工单自动创建")
    @RequestMapping(value = "/sk/create", method = RequestMethod.POST)
    public CommonResponse<Object> skCreate(@RequestBody JSONObject jsonObject){
        log.info("skCreate:{}",jsonObject.toJSONString());
        try {
            ConsoleSkRecordsList skData = jsonObject.getObject("skData", ConsoleSkRecordsList.class);
            UserServiceComboVO userServiceComboVO = jsonObject.getObject("userServiceCombo", UserServiceComboVO.class);
            MbpOrderCreateRequest req = new MbpOrderCreateRequest();
            BeanUtils.copyProperties(skData, req);
            Date date = new Date();
            // 使用SimpleDateFormat格式化日期
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String formattedDate = sdf.format(date);
            req.setBookDate(formattedDate);
            req.setIsSmartKitchen(true);
            req.setMemberId(Integer.parseInt(skData.getUserId()));
            req.setJvOrgCode("SU0105");
            req.setOrgCode("A129");
            req.setAddress(skData.getContactAddress());
            req.setStatus(2);
            req.setImei(skData.getDeviceId());
            req.setBizType(SkConst.SK_DEVICE_BIZ_TYPE_MAP.get(skData.getDeviceType()));
            req.setPhone(skData.getPhone() + (StringUtils.isEmpty(skData.getBackupPhone()) ? "" : ";" + skData.getBackupPhone()));
            req.setCustName(skData.getUserId());
            req.setSpId(skData.getSpId());
            req.setSkWorkSystemType(2);
            req.setUserServiceComboVO(userServiceComboVO);
            req.setIsAuto(1);

            //分布式锁，防止重复提交
            String key = Constants.ADD_EQUIPMENT + req.getImei();
            Boolean absent = redisUtil.setIfAbsent(key, String.valueOf(System.currentTimeMillis()), 5L);
            if (absent) {
                try {
                    mbpWorkOrderService.appealKitchenRecord(req);
                    //webSocket 给前端的参数
                    ConsoleSkNotifyAlarmResponse response = new ConsoleSkNotifyAlarmResponse();
                    BeanUtils.copyProperties(skData, response);
                    response.setNotifyName(ConsoleSkAlarmTypeEnum.getTypeByCode(skData.getAlarmType()));
                    response.setNotifyTime(skData.getAlarmTime());
                    response.setImei(skData.getDeviceId());
                    response.setInstallationPosition(skData.getRoomName());
                    response.setEquipmentTypeName(ConsoleSkDeviceTypeEnum.getTypeByCode(skData.getDeviceType()));
                    response.setPhone(skData.getPhone());
                    response.setNotifyName("自动转单");
                    response.setNotifyReason(BrowserNotifyReason.SkOrderAutoGen);
                    response.setIsPop(true);
                    response.setIsSystem(true);
                    response.setMemberId(response.getUserId());
                    response.setNotifyTime(DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
                    webSocketProcess.redisTopicSendMsg(req.getSpId(), JSONObject.toJSONString(response));
                    return CommonResponse.success(null);
                } catch (Exception e) {
                    return CommonResponse.failure(e.getMessage());
                } finally {
                    redisUtil.del(key);
                }
            } else {
                return CommonResponse.success("重复提交，不处理");
            }
        }catch (Exception e){
            log.error("skCreate error",e);
            return CommonResponse.failure(e.getMessage());
        }
    }

    @ApiOperation("查询联系人信息")
    @RequestMapping(value = "contact/list", method = RequestMethod.POST)
    public CommonResponse<List<ContactsListResponse>> getContactsList(@RequestBody @Valid ContactsListRequest request){
        List<ContactsListResponse> contactsResponses = syncOrderService.getContactsList(request);
        return CommonResponse.success(contactsResponses);
    }

    @ApiOperation("修改联系人信息")
    @RequestMapping(value = "contact/edit", method = RequestMethod.POST)
    public CommonResponse<Object> editContacts(@RequestBody @Valid ContactsEditRequest request){
        syncOrderService.editContacts(request);
        return CommonResponse.success("sucess");
    }
}
